package com.huodongrili.calender.bg;

import com.huodongrili.calender.BuildConfig;
import com.huodongrili.calender.data.Constant;
import com.huodongrili.calender.data.DataPreferences;
import com.huodongrili.calender.util.ECLog;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

public class ScheduleService extends Service {
	
	private AlarmManager mAlarmManager ;
	private PendingIntent mPendingIntent;
	private DataPreferences mDpf;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		
		if(BuildConfig.DEBUG){
			ECLog.debug("ScheduleService onCreate....");
		}
		
		mDpf = DataPreferences.getInstance(getApplicationContext());
		
		mAlarmManager = (AlarmManager) this.getApplicationContext()
				.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(getApplicationContext(),OperaReceiver.class);
		intent.setAction(Constant.ACTION_SCHEDULE_EXECUTE_OPERSERVICE);
		//intent.setAction(Constant.BG_SERVICE_NAME);
		mPendingIntent = PendingIntent.getBroadcast(
				this.getApplicationContext(), 0, intent, 0);
		
		mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000*60*10, 1000*60*60*6, mPendingIntent);
		
		//mAlarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000*60*5, mPendingIntent);
		
		
	}
	
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		
		if(mAlarmManager ==  null){
			mAlarmManager = (AlarmManager) this.getApplicationContext()
					.getSystemService(Context.ALARM_SERVICE);
		}
		
		if(mPendingIntent!=null){
			mAlarmManager.cancel(mPendingIntent);
		}
		
		
		toScheduleTime();
		
		
		return START_STICKY;
	}
	
	
	private void toScheduleTime(){
		
		Intent intent = new Intent(getApplicationContext(),OperaReceiver.class);
		intent.setAction(Constant.ACTION_SCHEDULE_EXECUTE_OPERSERVICE);
		//intent.setAction(Constant.BG_SERVICE_NAME);
		mPendingIntent = PendingIntent.getBroadcast(
				this.getApplicationContext(), 0, intent, 0);
		
		mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000*30, 1000*60*60*6, mPendingIntent);
		
	}
	
	
	
	@Override
	public void onDestroy() {
		
		if(BuildConfig.DEBUG){
			ECLog.debug("ScheduleService onDestory....");
		}
		
		mAlarmManager.cancel(mPendingIntent);
		
		super.onDestroy();
	}

}
